package com.leyou.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.entity.ClientInfo;
import com.leyou.auth.mapper.ClientAuthMapper;
import com.leyou.auth.service.ClientAuthService;
import com.leyou.common.exceptions.LyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class ClientAuthServiceImpl extends ServiceImpl<ClientAuthMapper, ClientInfo> implements ClientAuthService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${ly.jwt.key}")
    private String key;

    @Override
    public String getJwtKey(String clientId, String secret) {
        //根据clientId查询客户端信息
        ClientInfo clientInfo = query().eq("client_id", clientId).one();
        //判断客户端信息是否存在
        if (clientInfo == null){
            throw new LyException(401 , "客户端不存在或秘钥错误");
        }
        //比较secret
        if (!passwordEncoder.matches(secret,clientInfo.getSecret())){
            throw new LyException(401 , "客户端不存在或秘钥错误");
        }
        //返回秘钥
        return key;
    }
}
